package com.hefan.oms.task;

import com.alibaba.fastjson.JSON;
import com.hefan.oms.config.OmsConfigCenter;
import com.hefan.oms.itf.AnchorTicketMonthService;
import com.hefan.oms.itf.InComeService;
import com.hefan.schedule.model.ScheduleExecuteRecord;
import com.hefan.schedule.model.ScheduleServer;
import com.hefan.schedule.service.IScheduleExecuteRecordService;
import com.hefan.schedule.service.IScheduleTaskDeal;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/*
*Created by wangchao on 2016/12/28.
*统计前一天主播收入：月表、每次直播收入和历史收入
*/
@Service("anchorIncomeTask")
public class AnchorIncomeStatisticsTask implements IScheduleTaskDeal {

  private static Logger logger = LoggerFactory.getLogger(AnchorIncomeStatisticsTask.class);

  @Resource
  private IScheduleExecuteRecordService scheduleExecuteRecordService;
  @Resource
  private InComeService inComeService;
  @Resource
  private AnchorTicketMonthService anchorTicketMonthService;

  @Resource
  private OmsConfigCenter omsConfigCenter;
  /*
   * 主播月收入定时任务 0 10 0/3 * * ?
   * 每隔3小时执行一次
   * @param scheduleServer
   * @author wangchao
   * @version 1.0.0
   * @since 2016/10/31 下午12:25:16
  */
  @Override
  public boolean execute(ScheduleServer scheduleServer) {
    ScheduleExecuteRecord scheduleExecuteRecord = new ScheduleExecuteRecord();
    scheduleExecuteRecord.setExecuteTime(new Date());
    long startTime = System.currentTimeMillis();
    boolean rst = true;
    //1.统计收入时间区间比例
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR_OF_DAY, -1);
    DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:59:59");
    String end = dateFormat2.format(cal.getTime());
    cal.add(Calendar.HOUR_OF_DAY, -2);
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
    DateFormat dateFormat3 = new SimpleDateFormat("yyyyMM");
    //由于线上数据是1天执行一次，现改为3小时导致项目上线后会丢失一部分数据：处理逻辑如下：
    //第一次执行开始时间从配置中心获取，之后通过程序控制；
    Map<String, String> publicConfig = omsConfigCenter.getPublicConfig();
    String startConfig=publicConfig.get("startConfig");
    String start = StringUtils.isBlank(startConfig) ? dateFormat.format(cal.getTime()) : startConfig;
    int month = Integer.parseInt(dateFormat3.format(cal.getTime()));
    int successCount = 0;
    int failCount = 0;
    //2.查询前3小时所有收入
    List<Map<String, Object>> list = inComeService.getUserIncomeByDay(start, end);
    if (!CollectionUtils.isEmpty(list)) {
      //3.遍历每次主播收入
      for (Map<String, Object> map : list) {
        try {
          if (CollectionUtils.isEmpty(map) || !map.containsKey("type") || !map.containsKey("hefanNum") || !map.containsKey("userId")) {
            logger.error("统计主播收入异常map={}", JSON.toJSONString(map));
            break;
          }
          long balance = map.get("hefanNum") == null ? 0 : Long.parseLong(map.get("hefanNum").toString());
          //真实 or 虚拟饭票
          boolean isTrue = "1".equals(map.get("type").toString());
          anchorTicketMonthService.updateAnchorMonth(String.valueOf(map.get("userId")), balance, isTrue, month);
          successCount++;
        } catch (Exception e) {
          logger.error("主播月收入异常", e);
          failCount++;
          rst = false;
        }
      }
    }
    long endTime = System.currentTimeMillis();
    scheduleExecuteRecord.setConsumingTime((endTime - startTime));
    scheduleExecuteRecord.setNextExecuteTime(scheduleServer.getNextRunStartTime());
    scheduleExecuteRecord.setTaskType(scheduleServer.getBaseTaskType());
    scheduleExecuteRecord.setStatus(rst ? (short) 1 : (short) 2);
    scheduleExecuteRecord.setExecuteResult(String.format("主播月收入，成功处理%s条，失败%s条", successCount, failCount));
    scheduleExecuteRecord.setHostName(scheduleServer.getHostName());
    scheduleExecuteRecord.setIp(scheduleServer.getIp());
    scheduleExecuteRecordService.addScheduleExecuteRecord(scheduleExecuteRecord);
    return true;
  }

}
